package cn.com.anypay.manager.controller.sdk;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import cn.com.anypay.manager.config.LeshuaConfig;
import cn.com.anypay.manager.dto.config.payment.AlipayAppConfig;
import cn.com.anypay.manager.dto.config.payment.AlipayMerchantConfig;
import cn.com.anypay.manager.dto.config.payment.WxAppConfig;
import cn.com.anypay.manager.dto.config.payment.WxpayMerchantConfig;
import cn.com.anypay.manager.dto.config.payment.WxpayServiceProviderConfig;
import cn.com.anypay.manager.common.utils.SignUtils;

import java.util.*;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api/merchant")
public class MerchantController {
    private static final Logger log = LoggerFactory.getLogger(MerchantController.class);

    @Autowired
    @Qualifier("wxPayMiniappConfig")
    private WxAppConfig miniappConfig;  // 小程序配置

    @Autowired
    @Qualifier("wxPayMpConfig")
    private WxAppConfig mpConfig;       // 公众号配置

    @Autowired
    @Qualifier("wxPayMerchantConfig")
    private WxpayMerchantConfig wxPayMerchantConfig;

    @Autowired
    @Qualifier("wxPayServiceProviderConfig")
    private WxpayServiceProviderConfig wxPayServiceProviderConfig;

    @Autowired
    @Qualifier("alipayAppConfig")
    private AlipayAppConfig alipayAppConfig;

    @Autowired
    @Qualifier("alipayMerchantConfig")
    private AlipayMerchantConfig alipayMerchantConfig;

    @Autowired
    @Qualifier("alipaySubMerchantConfig")
    private AlipayMerchantConfig alipaySubMerchantConfig;

    @Autowired
    @Qualifier("alipayIsvAppConfig")
    private AlipayAppConfig isvAppConfig;

    @Autowired
    private LeshuaConfig leshuaConfig;

    // 生成商户ID
    @GetMapping("/generate-id")
    public Map<String, String> generateMerchantId() {
        String merchantId = UUID.randomUUID().toString().replace("-", "");
        return Map.of("merchantId", merchantId);
    }

    // 生成签名
    @PostMapping("/generate-sign")
    public Map<String, String> generateSign(@RequestBody Map<String, String> params) {
        try {
            log.info("=== 生成签名开始 ===");
            log.info("原始参数: {}", params);

            // 1. 参数排序
            Map<String, String> sortedParams = new TreeMap<>(params);
            sortedParams.remove("sign"); // 移除sign参数
            log.info("排序后参数: {}", sortedParams);

            // 2. 拼接参数
            String signStr = sortedParams.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
            log.info("拼接后字符串: {}", signStr);

            // 3. 添加商户密钥
            String mchKey = wxPayMerchantConfig.getMchApiKeyV2();
            log.info("商户密钥V2: {}", mchKey);
            signStr += "&key=" + mchKey;
            log.info("添加密钥后字符串: {}", signStr);

            // 4. 生成签名（使用SHA256）
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(signStr.getBytes(StandardCharsets.UTF_8));
            String sign = Base64.getEncoder().encodeToString(hash).toUpperCase();
            log.info("生成的签名: {}", sign);
            log.info("=== 生成签名结束 ===");

            return Map.of("sign", sign);
        } catch (Exception e) {
            log.error("生成签名失败: {}", e.getMessage(), e);
            throw new RuntimeException("生成签名失败", e);
        }
    }

    // 查看配置信息
    @GetMapping("/config")
    public String getConfig() {
        StringBuilder sb = new StringBuilder();
        sb.append("<pre>");  // 使用pre标签保持格式
        sb.append("=== AnyPay Manager 配置信息 ===\n\n");

        // 打印小程序配置
        sb.append("【小程序配置】\n");
        sb.append("应用类型: ").append(miniappConfig.getType()).append("\n");
        sb.append("AppID: ").append(miniappConfig.getAppId()).append("\n");
        sb.append("AppSecret: ").append(miniappConfig.getSecret()).append("\n");
        sb.append("Token: ").append(miniappConfig.getToken()).append("\n");
        sb.append("EncodingAESKey: ").append(miniappConfig.getEncodingAesKey()).append("\n");
        sb.append("消息格式: ").append(miniappConfig.getMsgDataFormat()).append("\n");
        sb.append("\n");

        // 打印公众号配置
        sb.append("【公众号配置】\n");
        sb.append("应用类型: ").append(mpConfig.getType()).append("\n");
        sb.append("AppID: ").append(mpConfig.getAppId()).append("\n");
        sb.append("AppSecret: ").append(mpConfig.getSecret()).append("\n");
        sb.append("Token: ").append(mpConfig.getToken()).append("\n");
        sb.append("EncodingAESKey: ").append(mpConfig.getEncodingAesKey()).append("\n");
        sb.append("消息格式: ").append(mpConfig.getMsgDataFormat()).append("\n");
        sb.append("\n");

        // 打印商户配置
        sb.append("【微信商户配置】\n");
        sb.append("商户号: ").append(wxPayMerchantConfig.getMchId()).append("\n");
        sb.append("商户API密钥V2: ").append(maskKey(wxPayMerchantConfig.getMchApiKeyV2())).append("\n");
        sb.append("商户API密钥V3: ").append(maskKey(wxPayMerchantConfig.getMchApiKeyV3())).append("\n");
        sb.append("商户证书序列号: ").append(wxPayMerchantConfig.getMchSerialNo()).append("\n");
        sb.append("商户API证书路径: ").append(wxPayMerchantConfig.getCertPath()).append("\n");
        sb.append("商户API证书密码: ").append(wxPayMerchantConfig.getCertPassword()).append("\n");
        sb.append("商户私钥路径: ").append(wxPayMerchantConfig.getPrivateKeyPath()).append("\n");
        sb.append("商户公钥路径: ").append(wxPayMerchantConfig.getPublicKeyPath()).append("\n");
        sb.append("平台证书路径: ").append(wxPayMerchantConfig.getPlatformCertPath()).append("\n");
        sb.append("回调地址: ").append(wxPayMerchantConfig.getNotifyUrl()).append("\n");
        sb.append("API版本: ").append(wxPayMerchantConfig.getApiVersion()).append("\n");
        sb.append("API域名: ").append(wxPayMerchantConfig.getDomain()).append("\n");
        sb.append("连接超时: ").append(wxPayMerchantConfig.getConnectTimeout()).append("ms\n");
        sb.append("读取超时: ").append(wxPayMerchantConfig.getReadTimeout()).append("ms\n");
        sb.append("写入超时: ").append(wxPayMerchantConfig.getWriteTimeout()).append("ms\n");
        sb.append("\n");

        // 打印服务商配置
        sb.append("【微信服务商配置】\n");
        sb.append("服务商商户号: ").append(wxPayServiceProviderConfig.getMchId()).append("\n");
        sb.append("服务商API密钥V2: ").append(maskKey(wxPayServiceProviderConfig.getMchApiKeyV2())).append("\n");
        sb.append("服务商API密钥V3: ").append(maskKey(wxPayServiceProviderConfig.getMchApiKeyV3())).append("\n");
        sb.append("服务商证书序列号: ").append(wxPayServiceProviderConfig.getMchSerialNo()).append("\n");
        sb.append("服务商API证书路径: ").append(wxPayServiceProviderConfig.getCertPath()).append("\n");
        sb.append("服务商API证书密码: ").append(wxPayServiceProviderConfig.getCertPassword()).append("\n");
        sb.append("服务商私钥路径: ").append(wxPayServiceProviderConfig.getPrivateKeyPath()).append("\n");
        sb.append("服务商公钥路径: ").append(wxPayServiceProviderConfig.getPublicKeyPath()).append("\n");
        sb.append("平台证书路径: ").append(wxPayServiceProviderConfig.getPlatformCertPath()).append("\n");
        sb.append("回调地址: ").append(wxPayServiceProviderConfig.getNotifyUrl()).append("\n");
        sb.append("API版本: ").append(wxPayServiceProviderConfig.getApiVersion()).append("\n");
        sb.append("API域名: ").append(wxPayServiceProviderConfig.getDomain()).append("\n");
        sb.append("连接超时: ").append(wxPayServiceProviderConfig.getConnectTimeout()).append("ms\n");
        sb.append("读取超时: ").append(wxPayServiceProviderConfig.getReadTimeout()).append("ms\n");
        sb.append("写入超时: ").append(wxPayServiceProviderConfig.getWriteTimeout()).append("ms\n");
        sb.append("\n");

        // 打印特约商户配置
        if (wxPayServiceProviderConfig.getSubMerchants() != null && !wxPayServiceProviderConfig.getSubMerchants().isEmpty()) {
            sb.append("【微信特约商户配置】\n");
            for (Map.Entry<String, WxpayServiceProviderConfig.SubMerchantConfig> entry : wxPayServiceProviderConfig.getSubMerchants().entrySet()) {
                String merchantKey = entry.getKey();
                WxpayServiceProviderConfig.SubMerchantConfig subMerchant = entry.getValue();
                sb.append("商户标识: ").append(merchantKey).append("\n");
                sb.append("特约商户号: ").append(subMerchant.getMchId()).append("\n");
                sb.append("\n");
            }
        }

        // 打印支付宝应用配置
        sb.append("【支付宝应用配置】\n");
        sb.append("AppID: ").append(alipayAppConfig.getAppId()).append("\n");
        sb.append("应用私钥: ").append(maskKey(alipayAppConfig.getPrivateKey())).append("\n");
        sb.append("支付宝公钥: ").append(maskKey(alipayAppConfig.getAlipayPublicKey())).append("\n");
        sb.append("网关地址: ").append(alipayAppConfig.getGateway()).append("\n");
        sb.append("回调地址: ").append(alipayAppConfig.getNotifyUrl()).append("\n");
        sb.append("沙箱模式: ").append(alipayAppConfig.getSandboxEnabled()).append("\n");
        sb.append("\n");

        // 打印支付宝ISV应用配置
        sb.append("【支付宝ISV应用配置】\n");
        sb.append("AppID: ").append(isvAppConfig.getAppId()).append("\n");
        sb.append("应用私钥: ").append(maskKey(isvAppConfig.getPrivateKey())).append("\n");
        sb.append("支付宝公钥: ").append(maskKey(isvAppConfig.getAlipayPublicKey())).append("\n");
        sb.append("网关地址: ").append(isvAppConfig.getGateway()).append("\n");
        sb.append("回调地址: ").append(isvAppConfig.getNotifyUrl()).append("\n");
        sb.append("沙箱模式: ").append(isvAppConfig.getSandboxEnabled()).append("\n");
        sb.append("\n");

        // 打印支付宝普通商户配置
        sb.append("【支付宝普通商户配置】\n");
        sb.append("商户PID: ").append(alipayMerchantConfig.getPid()).append("\n");
        sb.append("商户卖家ID: ").append(alipayMerchantConfig.getSellerId()).append("\n");
        sb.append("\n");

        // 打印支付宝特约商户配置
        sb.append("【支付宝特约商户配置】\n");
        sb.append("服务商PID: ").append(alipaySubMerchantConfig.getPid()).append("\n");
        sb.append("特约商户卖家ID: ").append(alipaySubMerchantConfig.getSellerId()).append("\n");
        sb.append("\n");

        // 打印乐刷支付配置
        sb.append("【乐刷支付配置】\n");
        sb.append("服务商ID: ").append(leshuaConfig.getServiceId()).append("\n");
        sb.append("服务商进件密钥: ").append(maskKey(leshuaConfig.getServiceApplyKey())).append("\n");
        sb.append("服务商交易密钥: ").append(maskKey(leshuaConfig.getServiceTradeKey())).append("\n");
        sb.append("服务商异步通知回调密钥: ").append(maskKey(leshuaConfig.getServiceNotifyKey())).append("\n");
        sb.append("商户ID: ").append(leshuaConfig.getMerchantId()).append("\n");
        sb.append("支付回调地址: ").append(leshuaConfig.getNotifyUrl()).append("\n");
        sb.append("支付跳转地址: ").append(leshuaConfig.getJumpUrl()).append("\n");
        sb.append("最小支付金额: ").append(leshuaConfig.getMinAmount()).append("元\n");
        sb.append("最大支付金额: ").append(leshuaConfig.getMaxAmount()).append("元\n");
        sb.append("支付超时时间: ").append(leshuaConfig.getTimeoutMinutes()).append("分钟\n");
        sb.append("\n");

        sb.append("</pre>");

        return sb.toString();
    }

    // 密钥脱敏处理
    private String maskKey(String key) {
        if (key == null || key.length() <= 16) {
            return "******";
        }
        return key.substring(0, 8) + "****" + key.substring(key.length() - 8);
    }

    // 验证商户请求签名
    @PostMapping("/verify-sign")
    public Map<String, Object> verifyMerchantRequestSignature(@RequestBody Map<String, String> params) {
        try {
            log.info("=== 验证商户请求签名开始 ===");
            log.info("请求参数: {}", params);

            // 使用工具类验证签名
            boolean isValid = SignUtils.verifySign(params, wxPayMerchantConfig.getMchApiKeyV2());
            log.info("签名验证结果: {}", isValid ? "成功" : "失败");

            if (isValid) {
                return Map.of(
                    "code", 0,
                    "message", "签名验证成功"
                );
            } else {
                return Map.of(
                    "code", -1,
                    "message", "签名验证失败"
                );
            }
        } catch (Exception e) {
            log.error("验证商户请求签名失败: {}", e.getMessage(), e);
            return Map.of(
                "code", -1,
                "message", "验证商户请求签名失败: " + e.getMessage()
            );
        }
    }
}